package com.tengju.user.domain.shared;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author: Dylan
 * @date: 2021/8/19 6:39 下午
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class FormComponent {
    String code;

    String title;

    FormComponentType type;

    List<ConfigContent> configContent;

    Boolean hasFilled;

    Object filledData;

    Boolean readOnly;

    Boolean required;

    Boolean searchable;

    /**
     * 构建默认的form组件, 文本,可以填充默认值,允许为空,
     *
     * @param code 后端传输code
     * @param title 前端展示title
     * @param value 组件默认填充值
     * @return 初始化默认组件
     */
    public static FormComponent of(String code, String title, Object value) {
        FormComponent formComponent = new FormComponent();
        formComponent.setCode(code);
        formComponent.setTitle(title);
        formComponent.setFilledData(value);
        formComponent.setType(FormComponentType.text);
        formComponent.setConfigContent(null);
        formComponent.setHasFilled(true);
        formComponent.setReadOnly(false);
        formComponent.setRequired(false);
        formComponent.setSearchable(false);
        return formComponent;
    }

    /**
     * 将多个组件的类型批量转为纯文本text类型
     */
    public static void batchConvertComponentTypeToText(List<FormComponent> formComponentList) {
        if (CollectionUtils.isEmpty(formComponentList)) {
            return;
        }
        for (FormComponent vo : formComponentList) {
            if (FormComponentType.radio == vo.getType()) {
                vo.setType(FormComponentType.text);
            } else if (FormComponentType.select == vo.getType()) {
                vo.setType(FormComponentType.text);
            } else if (FormComponentType.html == vo.getType()) {
                vo.setType(FormComponentType.texthtml);
            }
        }
    }

    public static List<FormComponent> jsonToSetComponentData(String codeComponentJsonStr, List<FormComponent> formComponentList){
        Map<String, String> codeComponentMap = JsonUtil.toMap(codeComponentJsonStr);
        if (CollectionUtils.isEmpty(codeComponentMap)){
            throw new DomainException(DomainExceptionCode.INVALID_DATA);
        }
        return formComponentList.stream().peek(
                v -> {
                    if (codeComponentMap.containsKey(v.getCode())) {
                        v.setFilledData(codeComponentMap.get(v.getCode()));
                    }
                }
        ).collect(Collectors.toList());
    }

}
